package com.wy.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wy.common.result.Result;
import com.wy.common.utils.MD5;
import com.wy.model.entity.User;
import com.wy.model.vo.UserQueryVo;
import com.wy.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/admin/system/user")
public class UserController {
  @Autowired
  private UserService userService;

  //查询所有User
  @ApiOperation("查询所有用户接口")
  @GetMapping("findAll")
  public Result findAllUser(){
    List<User> list = userService.list();
    return Result.ok(list);
  }

  //用户列表
  @GetMapping("/{page}/{limit}")
  public Result list(@PathVariable Integer page,
                     @PathVariable Integer limit,
                     UserQueryVo userQueryVo){

    //创建page对象
    Page<User> pageParam = new Page<>(page,limit);
    //调用service方法
    IPage<User> pageModel = userService.selectPage(pageParam,userQueryVo);
    return Result.ok(pageModel);
  }

  //添加用户
  @PostMapping("save")
  public Result saveUser(@RequestBody User user){
    //把输入的密码进行MD5加密
    String encrypt = MD5.encrypt(user.getPassword());
    user.setPassword(encrypt);
    boolean isSuccess = userService.save(user);
    if (isSuccess){
      return Result.ok();
    }else {
      return Result.fail();
    }
  }

  //根据id查询
  @GetMapping("getuser/{id}")
  public Result getUser(@PathVariable Integer id){
    User user = userService.getById(id);
    return Result.ok(user);
  }

  //修改用户
  @PostMapping("update")
  public Result update(@RequestBody User user){
    boolean isSuccess = userService.updateById(user);
    if (isSuccess){
      return Result.ok();
    }else {
      return Result.fail();
    }
  }

  //删除User
  @DeleteMapping("remove/{id}")
  public Result removeUser(@PathVariable Integer id) {
    boolean isSuccess = userService.removeById(id);
    if (isSuccess){
      return Result.ok();
    }else {
      return Result.fail();
    }
  }

  //更改用户状态
  @GetMapping("updateStatus/{id}/{status}")
  public Result updateStatus(@PathVariable Integer id,
                              @PathVariable Integer status){
    userService.updateStatus(id,status);
    return Result.ok();
  }
}
